package com.micosco.taskremind.ui.handler;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.micosco.taskremind.R;
import com.micosco.taskremind.data.Task;
import com.micosco.taskremind.data.TaskList;

import java.time.Duration;
import java.time.LocalDateTime;

public class HighlightTaskRefreshHandler extends RefreshHandler {
    private Activity mainActivity;
    private boolean autoRefresh;

    public HighlightTaskRefreshHandler(Activity mainActivity) {
        this.mainActivity = mainActivity;
        this.autoRefresh = false;
    }

    @SuppressLint("DefaultLocale")
    @Override
    public void handleMessage(@NonNull Message msg) {
        TextView remainTimeView =
                mainActivity.findViewById(R.id.remain_time_view);
        TextView dueDate =
                mainActivity.findViewById(R.id.end_date_view);
        TextView subject =
                mainActivity.findViewById(R.id.subject_view);
        TextView title =
                mainActivity.findViewById(R.id.task_title_view);
        TextView connecter =
                mainActivity.findViewById(R.id.subject_title_connecter);
        Button detail =
                mainActivity.findViewById(R.id.show_detail_buttom);

        Task earliestDue = TaskList.getInstance().getEarliestDueTask();
        if (earliestDue == null) {
            remainTimeView.setText(R.string.noTask);
            dueDate.setText("");
            subject.setText("");
            title.setText("");
            connecter.setText("");
            detail.setVisibility(View.INVISIBLE);
        } else {
            title.setText(earliestDue.getTitle());
            subject.setText(earliestDue.getSubject());
            LocalDateTime deadline = earliestDue.getDeadline();
            dueDate.setText(String.format("%d-%d-%d",
                    deadline.getYear(), deadline.getMonth().getValue(), deadline.getDayOfMonth()));
            connecter.setText("-");

            Duration remainTime = earliestDue.remainingTime();
            remainTimeView.setText(
                    String.format("%d:%d:%d", remainTime.toHours(),
                            remainTime.toMinutes() % 60, remainTime.getSeconds() % 60));
            detail.setVisibility(View.VISIBLE);
        }

        if (autoRefresh) {
            sendEmptyMessageDelayed(0, 500);
        }
    }

    @Override
    public void startRefresh() {
        this.autoRefresh = true;
        sendEmptyMessage(0);
    }

    @Override
    public void stopRefresh() {
        this.autoRefresh = false;
    }
}
